import React, { useEffect, useState, useCallback } from 'react';
import { Form, Input, Button, Space, Table, Tag, type TableProps, message } from 'antd';
import { Sub } from '../Subscribe/addSubscribe';
import { 
  SearchOutlined, LinuxOutlined, TwitterOutlined,
  CheckCircleOutlined, CloseCircleOutlined, CheckOutlined
} from '@ant-design/icons';
const { Column } = Table;
import type { IOrder } from '../types/Order';
import http from '../api/http';
import './index.css';

interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

export default function Subscribe() {
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 3,
    total: 0,
  });

  const [data, setdata] = useState<Array<IOrder>>([]);
  const [form] = Form.useForm();
  const [name, Setname] = useState('');
  const [caid, Setcaid] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
 
  // 处理状态变更的函数
  const handleStatusChange = (record: IOrder, newStatus: string) => {
    // 特殊处理“开始体检”状态的时间校验
    if (newStatus === "正在体检") {
      // 1. 获取预约日期和当前日期
      const orderDateStr = record.orderDate;
      const currentDate = new Date();
      
      // 2. 解析预约日期
      const orderDate = new Date(orderDateStr);
      if (isNaN(orderDate.getTime())) {
        message.error("预约日期格式错误，无法验证");
        return;
      }

      // 3. 只比较年月日（忽略时分秒）
      const orderDateOnly = new Date(
        orderDate.getFullYear(),
        orderDate.getMonth(),
        orderDate.getDate()
      );
      const currentDateOnly = new Date(
        currentDate.getFullYear(),
        currentDate.getMonth(),
        currentDate.getDate()
      );

      // 4. 日期比较
      const timeDiff = orderDateOnly.getTime() - currentDateOnly.getTime();
      
      if (timeDiff > 0) {
        message.warning("未到预约日期，无法开始体检");
        return;
      } else if (timeDiff < 0) {
        message.warning("已过预约日期，无法开始体检");
        return;
      }
 
        http.post("Mexam",{id:0,tsetmealid:record.setmalId,tmemberid:record.mid})
    }

    // 保存原始状态用于回滚
    const originalData = [...data];
    
    // 先更新本地状态
    const updatedData = data.map(item => 
      item.id === record.id ? { ...item, orderStatus: newStatus } : item
    );
    setdata(updatedData);

    // 调用接口同步到后端
    http.put('Order', { id: record.id, status: newStatus })
      .then(res => {
        console.log(res.msg);
        message.success("状态更新成功");
      })
      .catch(err => {
        console.error("状态更新失败:", err);
        message.error("状态更新失败，请重试");
        // 失败时回滚状态
        setdata(originalData);
      });
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    Setname(e.target.value);
  };

  const caidChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    Setcaid(e.target.value);
  };

  const search = useCallback(() => {
    http.getList<IOrder>("Order", {
      name,
      caid,
      page: pagination.current,
      size: pagination.pageSize
    }).then(res => {
      setdata(res.data || []);
      setPagination(prev => ({
        ...prev,
        total: res.count || 0,
        current: res.page || prev.current,
      }));
    }).catch(err => {
      message.error("数据加载失败，请重试");
      console.error("获取订单列表失败:", err);
    });
  }, [name, caid, pagination.current, pagination.pageSize]);

  const handleSearch = () => {
    console.log("查询");
    search();
  };

  useEffect(() => {
    search();
  }, [search]);

  const handlePaginationChange: TableProps<IOrder>['onChange'] = (paginationParams) => {
    setPagination({
      current: paginationParams.current || 1,
      pageSize: paginationParams.pageSize || 10,
      total: pagination.total,
    });
  };

  return (
    <>
      <div style={{ maxWidth: 800, margin: '20px auto', padding: '0 16px' }}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          initialValues={{ name: '', caid: '' }}
        >
          <Form.Item name="name">
            <Input
              placeholder="请输入预约名"
              style={{ width: 200 }}
              onChange={handleInputChange}
            />
          </Form.Item>

          <Form.Item name="caid">
            <Input
              placeholder="请输入身份证"
              style={{ width: 200, marginLeft: 16 }}
              onChange={caidChange}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
                style={{ marginLeft: 16 }}
              >
                查询
              </Button>
            </Space>
          </Form.Item>
          <Form.Item>
            <Space>
              <Sub ff={handleSearch} visible={isModalOpen} />
            </Space>
          </Form.Item>
        </Form>
      </div>

      <Table<IOrder>
        dataSource={data}
        rowKey="id"
        pagination={{
          className: 'table-pagination-center',
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条数据`,
          pageSizeOptions: ['10', '20', '50'],
          size: 'middle',
        }}
        onChange={handlePaginationChange}
      >
        <Column title="档案号" dataIndex="fileNumber" key="fileNumber" />
        <Column title="姓名" dataIndex="name" key="name" />
        <Column title="身份证号码" dataIndex="idCard" key="idCard" />
        <Column title="手机号" dataIndex="phoneNumber" key="phoneNumber" />
        <Column title="性别" dataIndex="sex" key="sex" />
        <Column title="年龄" dataIndex="age" key="age" />
        <Column title="预约时间" dataIndex="orderDate" key="orderDate" />
        <Column title="预约类型" dataIndex="orderType" key="orderType" />
        <Column
          title="套餐名称"
          dataIndex="sname"
          key="sname"
          render={(sname) => <label>{sname?.substr(0, 4)}</label>}
        />
        <Column
          title="状态"
          dataIndex="orderStatus"
          key="orderStatus"
          render={(status: string) => {
            // 状态颜色映射
            const colorMap: Record<string, string> = {
              '未到诊': '#faad14',    // 橙色
              '已预约': '#55acee',    // 蓝色
              '正在体检': '#1890ff',  // 亮蓝
              '已完成': '#52c41a',    // 绿色
              '已取消': '#cd201f'     // 红色
            };
            return (
              <Tag icon={<TwitterOutlined />} color={colorMap[status] || '#cd201f'}>
                {status}
              </Tag>
            );
          }}
        />

        <Column
          title="操作"
          key="action"
          render={(_: any, record: IOrder) => (
            <Space size="small">
              {/* 未到诊状态 - 显示预约和取消预约按钮 */}
              {record.orderStatus === "未到诊" && (
                <>
                  <Button
                    type="primary"
                    icon={<CheckCircleOutlined />}
                    onClick={() => handleStatusChange(record, "已预约")}
                  >
                    预约
                  </Button>
                  <Button
                    danger
                    icon={<CloseCircleOutlined />}
                    onClick={() => handleStatusChange(record, "已取消")}
                  >
                    取消预约
                  </Button>
                </>
              )}

              {/* 已预约状态 - 显示开始体检按钮 */}
              {record.orderStatus === "已预约" && (
                <Button
                  variant="solid"
                  icon={<LinuxOutlined style={{ color: '#1890ff' }} />}
                  onClick={() => handleStatusChange(record, "正在体检")}
                >
                  开始体检
                </Button>
              )}

              {/* 开始体检状态 - 显示已完成按钮 */}
              {record.orderStatus === "正在体检" && (
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  onClick={() => handleStatusChange(record, "已完成")}
                >
                  已完成
                </Button>
              )}

              {/* 已完成/已取消状态 - 显示状态标签 */}
              {(record.orderStatus === "已完成" || record.orderStatus === "已取消") && (
                <Tag color={record.orderStatus === "已完成" ? "success" : "default"}>
                  {record.orderStatus}
                </Tag>
              )}
            </Space>
          )}
        />
      </Table>
    </>
  );
}